#encoding:utf-8
from flask import Blueprint,url_for,request,render_template,redirect,flash
from flask_login import login_required,logout_user,login_user,current_user
from webapp.form import LoginForm,ClientForm,StatusForm,InfosourceForm,CommodityForm,CostorderForm,SaleorderForm,SaleorderckForm,Updateuser,Adduser
from webapp.models import User,Infosource,Client,Status,Commodity,Costlist,Costorder,Salelist,Saleorder,Commodityck
from webapp.exis import db
from os import path
from werkzeug.security import generate_password_hash
admin = Blueprint('admin',__name__,static_folder='static',template_folder=path.join(path.pardir,'templates','admin'))

#首页
@admin.route('/')
@login_required
def index():
    return render_template('index.html')
    # return current_user.nickname


#登录系统
@admin.route('/login/',methods=['POST','GET'])
def login():
    #判断是否有用户登录，如果登录了就不让访问登录页面了
    try:
        if current_user.username:
            return redirect(url_for('admin.index'))
    except:
        pass

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user,form.remeberme.data)
            return redirect(request.args.get('next') or url_for('admin.index'))
        else:
            flash(u'登陆失败！用户名或密码错误，请重新登陆。', 'danger')
        if form.errors:
            flash(u'登陆失败，请尝试重新登陆.', 'danger')
    return render_template('login.html',form=form)

#添加客户
@admin.route('/add_client',methods=['POST','GET'])
@login_required
def add_client():
    form = ClientForm()
    #获取客户状态下拉列表
    status = [(st.id, st.name) for st in Status.query.all()]
    form.statuses.choices = status
    #获取客户来源信息列表
    infosource = [(ins.id, ins.name) for ins in Infosource.query.all()]
    form.infosources.choices=infosource

    if form.validate_on_submit():
        client = Client(name=form.name.data,
                        sex=form.sex.data,
                        phone1=form.phone1.data,
                        phone2=form.phone2.data,
                        wechat=form.wechat.data,
                        qq=form.qq.data,
                        brithdy=form.brithday.data,
                        address=form.address.data,
                        infosource_id=form.infosources.data,
                        status_id=form.statuses.data,
                        note=form.note.data
                        )
        db.session.add(client)
        db.session.commit()
        return redirect(url_for('admin.client_list'))

    return render_template('add_client.html',form=form)

#客户列表
@admin.route('/client_list/')
@login_required
def client_list():
    clients = Client.query.all()
    return render_template('client_list.html',clients=clients)

#状态管理
@admin.route('/status/',methods=['POST','GET'])
def status():
    form = StatusForm()
    statuses = Status.query.all()
    if form.validate_on_submit():
        statuss = Status(name=form.name.data)
        db.session.add(statuss)
        db.session.commit()
        return redirect(url_for('admin.status'))
    return render_template('status.html',statuses=statuses,form=form)

#删除状态
@admin.route('/delete_status')
def delete_status():
    id = request.args.get('id')
    status = Status.query.filter(Status.id==id).first()
    db.session.delete(status)
    db.session.commit()
    return redirect(url_for('admin.status'))
#编辑状态
@admin.route('/edit_status',methods=['GET','POST'])
@login_required
def edit_status():
    form = StatusForm()
    id = request.args.get('id')
    status = Status.query.filter(Status.id == id).first()
    if form.validate_on_submit():
        Status.query.filter_by(id=request.form.get('id')).update({'name':form.name.data})
        db.session.commit()
        return redirect(url_for('admin.status'))
    return render_template('edit_status.html',status=status,form=form)

#信息来源管理
@admin.route('/infosource/',methods=['POST','GET'])
@login_required
def infosource():
    form = InfosourceForm()
    infosources = Infosource.query.all()
    if form.validate_on_submit():
        infosource = Infosource(name=form.name.data)
        db.session.add(infosource)
        db.session.commit()
        return redirect(url_for('admin.infosource'))
    return render_template('infosource.html',infosources=infosources,form=form)

#删除信息来源
@admin.route('/delete_infosource')
@login_required
def delete_infosource():
    id = request.args.get('id')
    infosource = Infosource.query.filter(Infosource.id==id).first()
    db.session.delete(infosource)
    db.session.commit()
    return redirect(url_for('admin.infosource'))
#编辑信息来源
@admin.route('/edit_infosource',methods=['GET','POST'])
@login_required
def edit_infosource():
    form = InfosourceForm()
    id = request.args.get('id')
    infosource = Infosource.query.filter(Infosource.id == id).first()
    if form.validate_on_submit():
        Infosource.query.filter_by(id=request.form.get('id')).update({'name':form.name.data})
        db.session.commit()
        return redirect(url_for('admin.infosource'))
    return render_template('edit_infosource.html',infosource=infosource,form=form)

#添加商品信息表
@admin.route('/commodity/',methods=['POST','GET'])
@login_required
def commodity():
    form = CommodityForm()
    if form.validate_on_submit():
        commodity = Commodity(name=form.name.data,
                        tcode=form.tcode.data,
                        scode=form.scode.data,
                        xingh=form.xingh.data,
                        danw=form.danw.data,
                        shengcrq=form.shengcrq.data,
                        baozq=form.baozq.data,
                        pih=form.pih.data,
                        shengcdz=form.shengcdz.data,
                        shengcs=form.shengcs.data,
                        note=form.note.data
                        )
        db.session.add(commodity)
        db.session.commit()
        return redirect(url_for('admin.commodity_list'))
    return render_template('commodity.html',form=form)

#商品列表
@admin.route('/commodity_list')
@login_required
def commodity_list():
    commoditys = Commodity.query.all()
    return render_template('commodity_list.html',commoditys=commoditys)
#商品删除
@admin.route('/commodity_delete')
@login_required
def commodity_delete():
    id = request.args.get('id')
    commodity = Commodity.query.filter(id==id).first()
    db.session.delete(commodity)
    db.session.commit()
    return redirect(url_for('admin.commodity_list'))

#商品采购入库
@admin.route('/costorder/',methods=['POST','GET'])
@login_required
def costorder():
    form = CostorderForm()
    commodity = [(st.id, st.name) for st in Commodity.query.all()]
    form.commoditys.choices = commodity
    if form.validate_on_submit():
        #订单添加
        costorder = Costorder(caigsy=form.caigsy.data,
                              name=form.name.data,
                              caigbh=form.caigbh.data,
                              date=form.caigrq.data,
                              caigr=form.caigr.data,
                              note=form.note.data
                              )
        #循环获取多表单内容，价格多少就循环多少次
        #设置一个计数器
        num = 0
        for caijjg in form.caigjg.raw_data:
            #商品属性直接插入
            costlist = Costlist(caigjg=form.caigjg.raw_data[num],
                                caigsl=form.caigsl.raw_data[num],
                                commodity_id=form.commoditys.raw_data[num],
                                )
            costlist.costorders=costorder
            db.session.add(costlist)
            db.session.commit()
            num += 1
        return redirect(url_for('admin.costorder_list'))

    return render_template('costorder.html',form=form)

#采购入库列表
@admin.route('/costorder_list')
@login_required
def costorder_list():
    costorders = Costorder.query.all()
    return render_template('costorder_list.html',costorders=costorders)

#创建销售
@admin.route('/saleorder/',methods=['POST','GET'])
@login_required
def saleorder():
    form = SaleorderForm()
    commodity = [(st.id, st.name) for st in Commodity.query.all()]
    form.commoditys.choices = commodity
    client = [(cl.id, cl.name) for cl in Client.query.all()]
    form.clients.choices = client
    if form.validate_on_submit():
        #销售单
        saleorder = Saleorder(
                              salename=form.salename.data,
                              salebh=form.salebh.data,
                              saledate=form.saledate.data,
                              saler=form.saler.data,
                              client_id=form.clients.data
                              )
        #设置一个计数器
        num = 0
        for salejg in form.salejg.raw_data:
            #商品快照
            commodity = Commodity.query.filter(Commodity.id==form.commoditys.raw_data[num]).first()
            #商品属性直接插入
            salelist = Salelist(salejg= form.salejg.raw_data[num],
                                salesl=form.salesl.raw_data[num],
                                commodity_id=form.commoditys.raw_data[num],
                                saleorders=saleorder,
                                c_name=commodity.name,
                                c_tcode = commodity.tcode,
                                c_scode = commodity.scode,
                                c_xingh = commodity.xingh,
                                c_danw = commodity.danw,
                                c_shengcrq = commodity.shengcrq,
                                c_baozq = commodity.baozq,
                                c_pih = commodity.pih,
                                c_shengcdz = commodity.shengcdz,
                                c_shengcs = commodity.shengcs
                                )

            db.session.add(salelist)
            db.session.commit()
            num += 1
        return redirect(url_for('admin.saleorder_list'))

    return render_template('saleorder.html',form=form)

#销售列表
@admin.route('/saleorder_list')
@login_required
def saleorder_list():
    saleorders = Saleorder.query.all()

    return render_template('saleorder_list.html',saleorders=saleorders)

#库存列表
@admin.route('/cost/')
@login_required
def cost():
    commodity = Commodity.query.all()
    costs = {}
    #先得到商品的列表
    for commoditys in commodity:
        #通过商品来查找商品的采购数量
        caigsl = []
        for comlist in commoditys.costlists:
            caigsl.append(comlist.caigsl)
        #得到销售数量
        sales = []
        for salelist in commoditys.salelists:
            sales.append(salelist.salesl)
        #得到库存
        #定义一个库存的字典，存放商品的ID及得到的库存
        costs[commoditys.id] = sum(caigsl)-sum(sales)

    return render_template('costs.html',commodity=commodity,costs=costs)

#应收应付
#查询到所有的采购数量和价格为应付
#查询到所有的销售数量和价格为应收
@admin.route('/ysyf/')
@login_required
def ysyf():
    #应付款
    costlist = Costlist.query.all()
    costmonny = []
    for costlists in costlist:
        monny = costlists.caigjg*costlists.caigsl
        costmonny.append(monny)
    #得到应付款
    yf = sum(costmonny)
    #应收款
    salelist = Salelist.query.all()
    salemonny = []
    for salelists in salelist:
        salemonny.append(salelists.salesl*salelists.salejg)
    #得到应收款
    ys = sum(salemonny)
    return render_template('ysyf.html',ys=ys,yf=yf)

#销售统计
@admin.route('sale_count')
@login_required
def sale_count():
    sale_list = Salelist.query.all()
    return render_template('sale_count.html',sale_list=sale_list)

#销售排行 计划使用图形
@admin.route('/sale_ph/')
@login_required
def sale_ph():
    commodity = Commodity.query.all()
    costs = {}
    #先得到商品的列表
    for commoditys in commodity:
        #通过商品来查找商品的采购数量
        sales = []
        for salelist in commoditys.salelists:
            sales.append(salelist.salesl)
        #得到库存
        #定义一个库存的字典，存放商品的ID及得到的库存
        costs[commoditys.id] = sum(sales)
    return render_template('sale_ph.html',commodity=commodity,costs=costs)

#销售出库
#还需要判断是否已经出库
@admin.route('/sale_ck/',methods=['POST','GET'])
@login_required
def sale_ck():
    if request.args.get('order_id'):
        order_id = request.args.get('order_id')
        #查找到销售单
        order_num = Saleorder.query.filter(Saleorder.id==order_id).first()
        #查询是否有出库单
        if order_num.commoditycks:
            return u'已发货，请不要重复出库'
        form = SaleorderckForm()
        client = [(cl.id, cl.nickname) for cl in User.query.all()]
        form.fhr.choices = client
        if form.validate_on_submit():
            ck = Commodityck(kddh=form.kddh.data,
                             kdgs=form.kdgs.data,
                             user_id=form.fhr.data,
                             fhdate=form.cksj.data,
                             note=form.note.data,
                             saleorder_id=order_id
                             )
            db.session.add(ck)
            db.session.commit()
            return redirect(url_for('admin.sale_ck'))
        return render_template('sale_ck.html',form=form,order_num=order_num)
    else:
        order = Saleorder.query.all()
        return render_template('orderck.html',order=order)

#物流详情
@admin.route('/wlxq/')
@login_required
def wlxq():
    order_id = request.args.get('order_id')
    order = Saleorder.query.filter(Saleorder.id==order_id).first()
    return render_template('wlxq.html',order=order)

#帐号管理
@admin.route('/usermg/')
@login_required
def usermg():
    user = User.query.all()
    return render_template('usermg.html',user=user)

#修改密码
@admin.route('/update_user',methods=['GET','POST'])
@login_required
def update_user():
    user_id = request.args.get('user_id')
    user = User.query.filter(User.id == user_id).first()
    form = Updateuser()
    if form.validate_on_submit():
        if form.password1.data != form.password2.data:
            return u'两次输入的密码不一致'
        else:
            # User.query.filter_by(id=user_id).update({'password':form.password1.data})
            # db.session.commit()
            User.query.filter_by(id=user_id).update({"password_hash":generate_password_hash(form.password1.data)})
            db.session.commit()
            return redirect(url_for('admin.usermg'))
    return render_template('update_user.html',user=user,form=form)

#删除用户
@admin.route('/delete_user')
@login_required
def delete_user():
    user = User.query.filter(User.id == request.args.get('user_id')).first()
    db.session.delete(user)
    db.session.commit()
    return redirect(url_for('admin.usermg'))

#添加用户
@admin.route('/add_user',methods=['GET','POST'])
@login_required
def add_user():
    form = Adduser()
    if form.validate_on_submit():
        if form.password1.data != form.password2.data:
            return u'密码不一致'
        else:
            user = User(username=form.username.data,password=form.password1.data,nickname=form.nickname.data,email=form.email.data)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('admin.usermg'))
    return render_template('add_user.html',form=form)

#退出系统
@admin.route('/logout/')
@login_required
def logout():
    logout_user()
    return redirect(url_for('admin.login'))